using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using FredCK.FCKeditorV2;
using CMS.BIZ;
using System.Web.UI;

namespace CMS.Web.UI.UserControls
{
    public partial class MessageBox : UserControl
    {
        private BizMessage message;
        private BizMessageGroup messageGroup;

        protected UpdatePanel upMessageSend;
        protected TextBox tbMessageTitle;
        protected TextBox tbReceiver;
        protected DropDownList ddlGroup;
        protected Button bAddGroupToReceiver;
        protected FCKeditor wysiwygEditor;
        protected Button bSendMessage;

        protected Repeater repeaterMessage;

        protected PlaceHolder phMessageView;
        protected Label lMessageTitle;
        protected Label lMessageDate;
        protected Label lSender;
        protected Literal lMessageBody;

        protected Repeater repeaterGroup;

        protected UpdatePanel upGroupEditor;
        protected TextBox tbGroupName;
        protected Button bAddGroup;
        protected UpdatePanel upGroupUserEditor;
        protected TextBox tbGroupUserName;
        protected ListBox lbGroupUser;
        protected Button bAddGroupUser;
        protected Button bRemoveGroupUser;

        protected MessageBox()
        {
            base.Init += new EventHandler(MessageBox_Init);
        }

        void MessageBox_Init(object sender, EventArgs e)
        {
            string strDeleteGroup = Request.QueryString["DeleteGroup"];
            if (!string.IsNullOrEmpty(strDeleteGroup))
            {
                int id = int.Parse(strDeleteGroup);
                if (Page.BizMessageGroupProvider.Delete(id, Page.BizMembershipUser.MemberID))
                {
                    Page.BizMessageGroupItemProvider.Delete(id);
                }
                BindGroups();
            }
            string strDeleteMessage = Request.QueryString["Delete"];
            if (!string.IsNullOrEmpty(strDeleteMessage))
            {
                int id = int.Parse(strDeleteMessage);
                BizMessageState state = Page.BizMessageStateProvider.Read(id, Page.BizMembershipUser.MemberID);
                if (state.MessageDeleteDate == null)
                {
                    state.MessageDeleteDate = DateTime.Now;
                    state.MessageState = BizMessageState.MessageNotVisible;
                    Page.BizMessageStateProvider.Update(state);
                    BindMessages();
                }
            }

            if (bSendMessage != null) bSendMessage.Click += new EventHandler(SendMessage_Click);
            if (bAddGroup != null) bAddGroup.Click += new EventHandler(AddGroup_Click);
            if (bAddGroupUser != null) bAddGroupUser.Click += new EventHandler(AddGroupUser_Click);
            if (bRemoveGroupUser != null) bRemoveGroupUser.Click += new EventHandler(RemoveGroupUser_Click);
            if (bAddGroupToReceiver != null) bAddGroupToReceiver.Click += new EventHandler(AddGroupToReceiver_Click);
            if (!Page.IsPostBack)
            {
                SetMessageFromQueryString();
                SetGroupFromQueryString();
                BindMessages();
                BindGroups();
                if (messageGroup != null)
                {
                    tbGroupName.Text = messageGroup.GroupName;
                }
            }
            if (string.IsNullOrEmpty(Request.QueryString["Message"]))
            {
                phMessageView.Visible = false;
                upMessageSend.Visible = true;
            }
            else
            {
                phMessageView.Visible = true;
                upMessageSend.Visible = false;
            }
            if (string.IsNullOrEmpty(Request.QueryString["MessageGroup"]))
            {
                upGroupUserEditor.Visible = false;
            }
            else
            {
                upGroupUserEditor.Visible = true;
            }
        }

        void AddGroupToReceiver_Click(object sender, EventArgs e)
        {
            List<BizMembershipUser> users = Page.BizMembershipProvider.ReadAllInMessageGroup(int.Parse(ddlGroup.SelectedValue));
            foreach (BizMembershipUser user in users)
            {
                if (tbReceiver.Text.Trim().Length > 0) tbReceiver.Text += ", ";
                tbReceiver.Text += user.UserName;
            }
        }

        void RemoveGroupUser_Click(object sender, EventArgs e)
        {
            if (messageGroup == null) SetGroupFromQueryString();
            if (messageGroup == null) return;
            List<ListItem> items = new List<ListItem>();
            foreach (ListItem item in lbGroupUser.Items)
            {
                if (item.Selected)
                {
                    Page.BizMessageGroupItemProvider.Delete(messageGroup.MessageGroupID, int.Parse(item.Value));
                    items.Add(item);
                }
            }
            foreach (ListItem item in items)
            {
                lbGroupUser.Items.Remove(item);
            }
        }

        void AddGroupUser_Click(object sender, EventArgs e)
        {
            if (messageGroup == null) SetGroupFromQueryString();
            if (messageGroup == null) return;
            string[] arrayUserName = tbGroupUserName.Text.Split(new char[] { ',' });
            if (arrayUserName == null || arrayUserName.Length == 0) return;
            List<string> list = new List<string>();
            foreach (string str in arrayUserName)
            {
                string name = str.Trim();
                if(!string.IsNullOrEmpty(name)) list.Add(name);
            }
            if (list.Count == 0) return;
            List<BizMembershipUser> users = Page.BizMembershipProvider.ReadAllUserNameIn(list);
            BizMessageGroupItem item = new BizMessageGroupItem();
            item.MessageGroupID = messageGroup.MessageGroupID;
            List<BizMembershipUser> errors = new List<BizMembershipUser>();
            foreach (BizMembershipUser user in users)
            {
                item.MemberID = user.MemberID;
                try
                {
                    Page.BizMessageGroupItemProvider.Create(item);
                    lbGroupUser.Items.Add(new ListItem(user.UserName, user.MemberID.ToString()));
                }
                catch (Exception)
                {
                    errors.Add(user);
                }
            }
        }

        void AddGroup_Click(object sender, EventArgs e)
        {
            if (messageGroup == null) SetGroupFromQueryString();
            if (messageGroup != null)
            {
                messageGroup.GroupName = tbGroupName.Text;
                Page.BizMessageGroupProvider.Update(messageGroup);
            }
            else
            {
                messageGroup = new BizMessageGroup();
                messageGroup.MemberID = Page.BizMembershipUser.MemberID;
                messageGroup.GroupName = tbGroupName.Text;
                Page.BizMessageGroupProvider.Create(messageGroup);
            }
            BindGroups();
        }

        protected void SetGroupFromQueryString()
        {
            string strGroupID = Request.QueryString["MessageGroup"];
            if (!string.IsNullOrEmpty(strGroupID))
            {
                messageGroup = Page.BizMessageGroupProvider.ReadByMemberID(int.Parse(strGroupID),Page.BizMembershipUser.MemberID);
                if(!Page.IsPostBack) BindGroupItems();
            }
        }

        protected void SetMessageFromQueryString()
        {
            string strMessageID = Request.QueryString["Message"];
            if (!string.IsNullOrEmpty(strMessageID))
            {
                message = Page.BizMessageProvider.ReadByMemberID(int.Parse(strMessageID),Page.BizMembershipUser.MemberID);
            }
            if (message != null)
            {
                lMessageTitle.Text = message.MessageTitle;
                lSender.Text = message.Sender.UserName;
                lMessageBody.Text = message.MessageBody;
                lMessageDate.Text = message.MessageDate.ToString();
                BizMessageState state = Page.BizMessageStateProvider.Read(message.MessageID, Page.BizMembershipUser.MemberID);
                if (state.MessageViewDate == null)
                {
                    state.MessageViewDate = DateTime.Now;
                    Page.BizMessageStateProvider.Update(state);
                }
            }
        }

        private void BindGroupItems()
        {
            if (messageGroup == null) return;
            List<BizMembershipUser> users = Page.BizMembershipProvider.ReadAllInMessageGroup(messageGroup.MessageGroupID);
            lbGroupUser.DataSource = users;
            lbGroupUser.DataTextField = "UserName";
            lbGroupUser.DataValueField = "MemberID";
            lbGroupUser.DataBind();
        }

        private void BindGroups()
        {
            List<BizMessageGroup> groups = Page.BizMessageGroupProvider.ReadByMemberID(Page.BizMembershipUser.MemberID);
            ddlGroup.DataSource = groups;
            ddlGroup.DataTextField = "GroupName";
            ddlGroup.DataValueField = "MessageGroupID";
            ddlGroup.DataBind();
            repeaterGroup.DataSource = groups;
            repeaterGroup.DataBind();
        }

        private void BindMessages()
        {
            ///TODO ReadAllVisibleByMemberIDAndFolder
            List<BizMessageState> states = Page.BizMessageStateProvider.ReadAllWithMessageByMember(Page.BizMembershipUser.MemberID, BizMessageState.MessageVisible, null);
            //List<BizMessage> messages = Page.BizMessageProvider.ReadAllByMemberID(Page.BizMembershipUser.MemberID, 0, null);
            repeaterMessage.DataSource = states;
            repeaterMessage.DataBind();
        }

        void SendMessage_Click(object sender, EventArgs e)
        {
            string receivers = tbReceiver.Text;
            if (receivers.Trim().Length == 0) return;
            string[] arrayReceiver = receivers.Split(new char[] { ',' });
            List<string> listReceiver = new List<string>();
            foreach (string receiver in arrayReceiver)
            {
                string rcv = receiver.Trim();
                if(rcv.Length > 0) listReceiver.Add(rcv);
            }
            if (listReceiver.Count > 0)
            {
                List<BizMembershipUser> users = Page.BizMembershipProvider.ReadAllUserNameIn(listReceiver);
                if (users.Count > 0)
                {
                    BizMessage message = new BizMessage();
                    message.MessageBody = wysiwygEditor.Value;
                    message.MessageTitle = tbMessageTitle.Text;
                    message.SenderID = Page.BizMembershipUser.MemberID;
                    message.MessageDate = DateTime.Now;
                    if (Page.BizMessageProvider.Create(message))
                    {
                        BizMessageState state = new BizMessageState();
                        state.MessageID = message.MessageID;
                        foreach (BizMembershipUser user in users)
                        {
                            state.MemberID = user.MemberID;
                            Page.BizMessageStateProvider.Create(state);
                        }
                    }
                }
            }
        }

    }
}
